package com.esreport.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esreport.Utils.DateUtil;
import com.esreport.Utils.JSONUtil;
import com.esreport.dao.ReportRepository;
import com.esreport.entity.Report;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/es")
public class ReportController {

//    @Autowired
//    FileTracker<Report> fileTracker;

    @Autowired
    private ReportRepository reportRepository;

//    public void fff(){
//        ConcurrentLinkedQueue<Report> queue = fileTracker.getQueue();

//        while(true){
//            Report report = queue.poll();
//            if(report==null){
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                continue;
//            }
//        }
//    }

    @RequestMapping("/save")
    public String save() {
        String encoding = "GBK";

        try {
//            File file1 = new File("C:\\Users\\Administrator.SC-201708301319\\Desktop\\fsdownload\\20180614.log");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
            File[] files = new File("C:\\Users\\Administrator.SC-201708301319\\Desktop\\log").listFiles();
            List<Report> list = new ArrayList<Report>();
            String lineTxt = null;
            String ipAddress = null;
            String content = null;
            Report report = null;
            String fileName = null;
            for (File file:files) {
                fileName = file.getName();
                System.out.println("读取文件："+fileName);
                if(fileName.split("\\.")[fileName.split("\\.").length-1].equals("log")){//取log结尾的日志文件
                    InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
                     BufferedReader bufferedReader = new BufferedReader(read);
                    while ((lineTxt = bufferedReader.readLine()) != null) {
//                    System.out.println(lineTxt);
                        String seriseSign = UUID.randomUUID().toString();
                        ipAddress = lineTxt.split(" ")[0];
                        content = lineTxt.split(" ",2)[1];
                        if(!JSONUtil.isJsonArray(content)){
                            continue;//判断内容格式   可能不是jsonarray  如果不是跳出本次循环  进行开始下一次
                        }
                        JSONArray array = JSON.parseArray(content);
                        for (int i = 0;i<array.size();i++){
                            JSONObject json =  (JSONObject) array.get(i);
                            Date startDate = sf.parse((String) json.get("startTime"));
                            Date endDate;
                            if(json.get("endTime")!=null&&!json.get("endTime").equals("")){
                                endDate = sf.parse((String) json.get("endTime"));
                            }else{
                                endDate = null;
                            }
                            json.put("id",UUID.randomUUID().toString().replace("-", "").toLowerCase());
                            json.put("ip",ipAddress);
                            json.put("startTime",startDate);
                            json.put("endTime",endDate);
                            json.put("seriesSign",seriseSign);
                            report = JSON.toJavaObject(json,Report.class);
                            list.add(report);
                        }
                        if(list.size()>3000){
                            reportRepository.saveAll(list);
                            list.clear();
                        }
                    }
                    read.close();
                }
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 定时器  每天凌晨1点执行  将昨天的日志文件上传到ES
     */
//    @Scheduled(cron = "0 0 3 * * ?")
    public void reportTask(){
        String encoding = "GBK";
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMdd");
        String date = sf1.format(DateUtil.getNeedTime(0 ,0,0,-1));//获取昨天的日期
        System.out.println("读取文件："+date);
        try{
            List<Report> list = new ArrayList<Report>();
            String lineTxt = null;
            String ipAddress = null;
            String content = null;
            Report report = null;
            File file = new File("/data/report/"+date+".log");
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            while ((lineTxt = bufferedReader.readLine()) != null) {
//                    System.out.println(lineTxt);
                ipAddress = lineTxt.split(" ")[0];
                content = lineTxt.split(" ",2)[1];
                if(!JSONUtil.isJsonArray(content)){
                    continue;//判断内容格式   可能不是jsonarray  如果不是跳出本次循环  进行开始下一次
                }
                JSONArray array = JSON.parseArray(content);
                for(int i = 0;i<array.size();i++){
                    JSONObject json = (JSONObject) array.get(i);
                    Date startDate = sf.parse((String) json.get("startTime"));
                    Date endDate;
                    if(json.get("endTime")!=null&&!json.get("endTime").equals("")){
                        endDate = sf.parse((String) json.get("endTime"));
                    }else{
                        endDate = null;
                    }
                    json.put("id",UUID.randomUUID().toString().replace("-", "").toLowerCase());
                    json.put("ip",ipAddress);
                    json.put("startTime",startDate);
                    json.put("endTime",endDate);
                    report = JSON.toJavaObject(json,Report.class);
                    list.add(report);
                }
                if(list.size()>3000){
                    reportRepository.saveAll(list);
                    list.clear();
                }
            }
            read.close();
        }catch (Exception e){
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

}
